package com.ruoyi.app.company;

import com.ruoyi.app.business.login.TokenBusiness;
import com.ruoyi.app.config.util.UserUtil;
import com.ruoyi.app.converter.CompanyConverter;
import com.ruoyi.app.domain.company.CompanyDetail;
import com.ruoyi.app.domain.company.CompanyInfo;
import com.ruoyi.app.domain.company.CompanySave;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.common.core.utils.PageUtils;
import com.ruoyi.common.core.web.page.CommonPageInfo;
import com.ruoyi.service.company.entity.CompanyEntity;
import com.ruoyi.service.company.entity.UserCompanyEntity;
import com.ruoyi.service.company.enums.CheckStatusEnum;
import com.ruoyi.service.company.enums.UserRoleEnum;
import com.ruoyi.service.company.query.CompanyBaseQuery;
import com.ruoyi.service.company.service.CompanyService;
import com.ruoyi.service.company.service.UserCompanyService;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Optional;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 作用：公司业务类
 * </p>
 *
 * @author Zane
 * @since 2025-10-22 0:34
 */
@Component
public class CompanyBusiness {

  @Resource
  private CompanyService companyService;
  @Resource
  private UserCompanyService userCompanyService;
  @Autowired
  private TokenBusiness tokenBusiness;

  @Transactional(rollbackFor = Exception.class)
  public void saveCompany(CompanyEntity companyEntity) {
    companyService.save(companyEntity);
    //绑定公司设置管理员
    userCompanyService.save(new UserCompanyEntity()
        .setUserId(companyEntity.getManager())
        .setComId(companyEntity.getComId())
        .setUserRole(UserRoleEnum.ADMIN.getCode())
        .setCreateBy(companyEntity.getCreateBy())
        .setCreateTime(companyEntity.getCreateTime())
        .setUpdateBy(companyEntity.getUpdateBy())
        .setUpdateTime(companyEntity.getUpdateTime()));
  }

  public boolean companyExist(@NotNull(message = "统一社会信用码不能为空") String usci) {
    return companyService.companyExist(usci);
  }

  public void updateById(CompanyEntity company) {
    companyService.updateById(company);
  }

  public CompanyEntity getById(Long comId) {
    return companyService.getById(comId);
  }

  public void saveUserCompany(Long userId, Long comId, Long loginUserId) {
    userCompanyService.save(new UserCompanyEntity()
        .setUserId(userId)
        .setComId(comId)
        .setUserRole(UserRoleEnum.NORMAL.getCode())
        .setCreateBy(loginUserId)
        .setCreateTime(LocalDateTime.now())
        .setUpdateBy(loginUserId)
        .setUpdateTime(LocalDateTime.now()));
  }

  public UserCompanyEntity getUserCompanyByUserId(Long userId) {
    return userCompanyService.getByUserId(userId);
  }

  public Long countCompany() {
    return companyService.countCompany();
  }

  public Long getCompanyApproval() {
    return companyService.getCompanyApproval();
  }

  public CommonPageInfo<CompanyInfo> listNeedCheck(CompanyBaseQuery query) {
    final CommonPageInfo<CompanyEntity> page = PageUtils.startPage(query.getPageNum(),
        query.getPageSize());
    page.initData(Optional.ofNullable(companyService.selectListNeedCheck(query))
        .orElseGet(ArrayList::new));
    return page.convert(CompanyConverter.INSTANCE::toCompanyInfo);
  }

  public CompanyInfo companyCheckDetail(Long comId) {
    final CompanyEntity company = CommonUtils.requireNotNull(companyService.getById(comId),
        "公司ID不合法");
    return CompanyConverter.INSTANCE.toCompanyInfo(company);
  }

  public CompanyDetail myCompanyDetail() {
    final Long companyId = UserUtil.getLoginUser().getCompanyId();
    final CompanyEntity company = CommonUtils.requireNotNull(companyService.getById(companyId),
        "公司ID不合法");
    return CompanyConverter.INSTANCE.toCompanyDetail(company);
  }

  public void update(CompanySave companySave) {
    //判断公司是否是自己的公司
    final Long companyId = UserUtil.getLoginUser().getCompanyId();
    if (companyId.compareTo(companySave.getComId()) != 0) {
      throw new ServiceException("您不是公司管理员");
    }
    //
    final CompanyEntity sourceCompany = CommonUtils.requireNotNull(
        companyService.getById(companySave.getComId()), "公司ID不存在");
    if (CheckStatusEnum.PASSED.eqCode(sourceCompany.getStatus())) {
      throw new ServiceException("公司已通过审核，不能修改");
    }
    companyService.updateById(sourceCompany
        .setStatus(CheckStatusEnum.CHECKING.getCode())
        .setComName(companySave.getComName())
        .setUsci(companySave.getUsci())
        .setServBrand(companySave.getServBrand())
        .setComLicense(companySave.getComLicense())
        .setLinkUser(companySave.getLinkUser())
        .setLinkPhone(companySave.getLinkPhone())
        .setLinkIdCard(companySave.getLinkIdCard())
        .setUpdateBy(UserUtil.getUserId())
        .setUpdateTime(LocalDateTime.now()));
    companyService.updateById(sourceCompany);
    tokenBusiness.refreshUser(sourceCompany.getManager());
  }
}
